package com.lx.controller;

import com.lx.bean.User;
import com.lx.service.UserService;
import com.lx.vo.GenderCount;
import com.lx.vo.MyMap;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("user")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 注解中 consumes 表示传来的参数为 json 数据
     * @param user
     * @return
     */
    @PostMapping(value = "/registerUser", consumes = "application/json")
    public Map registerUser(@RequestBody User user){
        User user1 = userService.addUser(user);
        return MyMap.ok().put("user",user1);
    }

    @PostMapping("/userLogin")
    public Map userLogin(@RequestBody User user){
        System.out.println("user = " + user);
        User user1 = userService.queryUserByNameAndPassword(user);
        System.out.println("user1 = " + user1);
        return MyMap.ok().put("user",user);
    }

    //同添加方法
    @PutMapping(value = "/updateUser")
    public Map updateUser(@RequestBody User user){
        userService.updateUser(user);
        return MyMap.ok();
    }

    @DeleteMapping("/deleteUserByIds")
    public Map deleteUserByIds(@RequestBody Integer[] ids){
        userService.deleteByUserIds(ids);
        /*List<Integer> idList = new ArrayList<Integer>();
        for (char c : ids.toCharArray()) {
            if(Character.isDigit(c)){
                idList.add(Integer.parseInt(c+""));
            }
        }
        Integer[] ids = idList.toArray(new Integer[idList.size()]);*/
        return MyMap.ok();
    }
    @DeleteMapping("/deleteUserById/{id}")
    public Map deleteUserById(@PathVariable("id") Integer id){
        userService.deleteUserById(id);
        return MyMap.ok();
    }

    @GetMapping("/queryUserByPage")
    public List<User> queryUserByPage(@RequestParam(value = "pageIndex",defaultValue = "1") Integer pageIndex,
                                      @RequestParam(value = "rows",defaultValue = "10") Integer rows,
                                      @RequestParam(value = "column",required = false) String column,
                                      @RequestParam(value = "value",required = false) String value)
    {
        List<User> users = userService.queryUserByPage(pageIndex, rows, column, value);
        return users;
    }

    @GetMapping("/queryUserCount")
    public Integer queryUserCount(String column,String value){
        int totalPage = userService.queryUserCount(column, value);
        return totalPage;
    }

    @GetMapping("/queryUserById")
    public User queryUserById(Integer id){
        User user = userService.queryUserById(id);
        return user;
    }
    @GetMapping("genderCount")
    public List<GenderCount> genderCount(){
        List<GenderCount> genderCounts = userService.countGender();
        return genderCounts;
    }
}
